﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LinqToTwitter;
using System.Collections;

namespace Twitter.Util
{

    public class UserComparer : IEqualityComparer<LinqToTwitter.User>
    {

        public UserComparer()
        { }


        bool IEqualityComparer<LinqToTwitter.User>.Equals(LinqToTwitter.User x, LinqToTwitter.User y)
        {
            if (x.Identifier.UserID == y.Identifier.UserID)
                return true;
            return false;
        }

        int IEqualityComparer<LinqToTwitter.User>.GetHashCode(LinqToTwitter.User obj)
        {
            return obj.Identifier.UserID.GetHashCode();
        }
    }  


    public class UserTweets
    {

        private HttpRequest request;
        private HttpResponse response;
        private String userid;

        public UserTweets(HttpRequest request, HttpResponse response, String userid)
        {
            this.request = request;
            this.response = response;
            this.userid = userid;       
        }

        public List<Status> getTweets(WebAuthorizer auth)
        {
            TwitterContext twitterCtx = new TwitterContext(auth);
            var lst =
                  (from tweet in twitterCtx.Status
                   where tweet.Type == StatusType.Home
                   && tweet.Count == 40
                   select tweet).ToList();
            return lst;
        }

        public List<Status> getUserTweets(String user, WebAuthorizer auth)
        {
            TwitterContext twitterCtx = new TwitterContext(auth);

            var lst =
                  (from tweet in twitterCtx.Status
                   where tweet.Type == StatusType.Public
                    && tweet.Count == 40
                   select tweet).ToList();
            return lst;
        }

        public void doTweet(String text, WebAuthorizer auth)
        {
            if (text == "")
                return;
            try
            {
                TwitterContext twitterCtx = new TwitterContext(auth);
                twitterCtx.UpdateStatus(text);
            }
            catch (Exception ex)
            { }
        
        }

        public IEnumerable<LinqToTwitter.User> getFriend(WebAuthorizer auth)
        {
            TwitterContext twitterCtx = new TwitterContext(auth);

           var friendTweets =
                (from tweet in twitterCtx.Status
                 where tweet.Type == StatusType.Friends
                 select tweet.User)
                .Distinct<LinqToTwitter.User>(new UserComparer()).ToList();

           return friendTweets.Distinct<LinqToTwitter.User>(new UserComparer());
        }


        public IEnumerable<LinqToTwitter.Status> getFriendTweets(WebAuthorizer auth, String userid)
        {
            TwitterContext twitterCtx = new TwitterContext(auth);

            var friendTweets =
                 (from tweet in twitterCtx.Status
                  where tweet.Type == StatusType.Home
                  && tweet.User.Identifier.UserID == userid
                   && tweet.Count == 40
                  select tweet)
                 .ToList();

            return friendTweets;
        }

        public User updateUser( LinqToTwitter.User usr)
        {
            TwitterEntitiesModelContainer context = new TwitterEntitiesModelContainer();//)
            {
                User user = (from u in context.UserJeu
                             where u.screenName == usr.Identifier.ScreenName
                             select u).FirstOrDefault<User>();
                if (user != null)
                    return user;

                user = new User();
                user.screenName = usr.Identifier.ScreenName;
                user.name = usr.Identifier.ScreenName;
                user.userId = usr.Identifier.UserID;
                user.profileUrl = usr.ProfileImageUrl;

                context.UserJeu.AddObject(user);
                context.SaveChanges();
                return user;


            }
        }

        private List<DateTime> getLastUserSavedTweetDate(User user)
        {
           using(TwitterEntitiesModelContainer context = new TwitterEntitiesModelContainer())
           {
               List<DateTime> dtime = (from d in context.TweetJeu
                                 where d.User.ID == user.ID
                                 orderby d.creationDate descending
                                 select d.creationDate).ToList<DateTime>();
               if (dtime == null || dtime.Count == 0)
                   return null;

               return dtime;
           }
        }


        public bool PersistTweets(WebAuthorizer auth, LinqToTwitter.User user, String Memberlogin)
        {
            String userId = user.Identifier.UserID;
            IEnumerable<LinqToTwitter.Status> tweets = getFriendTweets(auth, userId);

            using(TwitterEntitiesModelContainer context = new TwitterEntitiesModelContainer())
            {
                Member member = (from m in context.MemberJeu
                                 where m.login == Memberlogin
                              select m).FirstOrDefault<Member>();
                if (member == null)
                {
                    throw new Exception("Member null");
                    //return false;
                }

                User mUser = updateUser(user); 
                // Ajout de l'entite dans le contexte
                mUser = (from u in context.UserJeu
                         where u.ID == mUser.ID
                         select u).First<User>();

                //On prend la date du dernier tweets enregistrer dans la base de données pour eviter les doublons
                bool existdate = getLastUserSavedTweetDate(mUser) == null ? false : true;
                DateTime lastDate = new DateTime(); ;
                if(existdate)
                 lastDate = getLastUserSavedTweetDate(mUser).First();

                foreach(Status status in tweets)
                {
                    if (existdate && lastDate >= status.CreatedAt)
                        continue;
                    Tweet tweet = new Tweet();
                    tweet.text = status.Text;
                    tweet.imgUrl = status.User.ProfileImageUrl;
                    tweet.creationDate = status.CreatedAt;
                    tweet.Member = member;
                    tweet.User = mUser;
                    context.TweetJeu.AddObject(tweet);
                    context.SaveChanges();
                }
                return true;
            }
        }

        public LinqToTwitter.User getUser(WebAuthorizer auth, String usrId)
        { 
             TwitterContext twitterCtx = new TwitterContext(auth);
             IEnumerable<LinqToTwitter.User> users = getFriend(auth);

             LinqToTwitter.User user = (from u in users
                          where u.Identifier.UserID == usrId
                                        select u).First<LinqToTwitter.User>();

             return user;
        }

        public LinqToTwitter.User getUserByName(WebAuthorizer auth, String name)
        {
            TwitterContext twitterCtx = new TwitterContext(auth);
            LinqToTwitter.User user = (from u in twitterCtx.User
                                       where u.Identifier.ScreenName == name
                                       || u.ScreenName == name
                                       && u.Type == UserType.Show
                                       select u).First<LinqToTwitter.User>();

            return user;
        }


        public void deleteTweet(WebAuthorizer auth, String tweetId)
        {
            try
            {
                TwitterContext twitterCtx = new TwitterContext(auth);
                twitterCtx.DestroyStatus(tweetId);
            }
            catch (Exception ex)
            { 
            }
        }

        public Status getTweet(WebAuthorizer auth, String tweetId)
        {
            TwitterContext twitterCtx = new TwitterContext(auth);
            Status status = (from s in twitterCtx.Status
                      where s.Type == StatusType.Home 
                             && s.StatusID == tweetId
                      select s).FirstOrDefault();

            return status;      
        }

    }
}